17. Exercise: Add a Filter
L8 33 Adding A Filter HS-SC
Erratum
At timestamp 01:25 onwards in the video above, inOverviewViewModel.ktfile, use the updated definition of thegetMarsRealEstateProperties()function as mentioned in the instructions below. Alternatively, you can check out the relevant branch of the Git repo.
Now it's your turn to complete this exercise yourself! If you want to start at this step, you can download this exercise from: Step.08-Exercise-Adding-a-Filter. You will find plenty of //TODO comments to help you complete things.
- In
MarsApiService, create aMarsApiFilterenumthat defines constants to match the query values our web service expects:
enum class MarsApiFilter(val value: String) { SHOW_RENT("rent"), SHOW_BUY("buy"), SHOW_ALL("all") }
- Add a
@Query("filter")parameter togetProperties()so we can filter properties based on theMarsApiFilterenum values:
fun getProperties(@Query("filter") type: String):
- In
OverviewViewModel, add aMarsApiFilterparameter togetMarsRealEstateProperties():
private fun getMarsRealEstateProperties(filter: MarsApiFilter) {
- Pass the
filter.valuetoretrofitService.getProperties():
_properties.value = MarsApi.retrofitService.getProperties(filter.value)
- In the
initblock, passMarsApiFilter.SHOW_ALLas the default parameter togetMarsRealEstateProperties():
getMarsRealEstateProperties(MarsApiFilter.SHOW_ALL)
- Now create an
updateFilter()method to requery the data by callinggetMarsRealEstatePropertieswith the new filter:
fun updateFilter(filter: MarsApiFilter) {
getMarsRealEstateProperties(filter)
}
In
OverviewFragment, we need to provide a menu option so the user can change the filter. OverrideonOptionsItemSelected()and pass the selected filterviewModel.updateFilter:override fun onOptionsItemSelected(item: MenuItem): Boolean { viewModel.updateFilter( when (item.itemId) { R.id.show_rent_menu -> MarsApiFilter.SHOW_RENT R.id.show_buy_menu -> MarsApiFilter.SHOW_BUY else -> MarsApiFilter.SHOW_ALL } ) return true }Run the app, use the new menu option to change the filter, and start searching for your new dream home on Mars!
If you get stuck, go back and watch the video again. Once you’re done, you can check your solution against the solution we’ve provided here: Step.08-Solution-Adding-a-Filter, or using this git diff.
Task Description:
Complete the tasks below to filter your real estate listings results.
Task Feedback:
Great job!
Reference documentation